package com.company.project.web;

import com.company.project.core.Result;
import com.company.project.core.ResultCode;
import com.company.project.core.ResultGenerator;
import com.company.project.model.User;
import com.company.project.utils.MD5Utils;
import com.google.common.collect.Maps;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author chenyang
 * @desc  登陆接口
 * @date 2017-07-24-11:05
 */
@RestController
@RequestMapping("index")
public class LoginController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());




    @PostMapping("login")
    public Result login(HttpSession session, @RequestParam(defaultValue = "") String username, @RequestParam(defaultValue = "") String password) {
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(username, MD5Utils.getMD5(password));
        Subject subject = SecurityUtils.getSubject();
        String token= MD5Utils.getMD5(System.currentTimeMillis()+"");
        Map data= Maps.newHashMap();
        try {
            subject.login(usernamePasswordToken);   //完成登录
            User user=(User) subject.getPrincipal();
            session.setAttribute("user", user);
            session.setAttribute("token",token);
            data.put("token",token);
            data.put("roles", user.getRoles());
        } catch (AuthenticationException e) {
            logger.error("登陆失败 username:"+username+" password:"+password+" msg:"+e.getMessage());
            Result result=new Result();
            result.setCode(ResultCode.FAIL).setMessage("用户名或者密码错误!");
            return result;
        }
        return ResultGenerator.genSuccessResult(data);
    }

    @RequestMapping(value = "unAuthentication",method = {RequestMethod.POST, RequestMethod.GET,RequestMethod.DELETE,RequestMethod.PUT})
    public Result unAuthentication() {
        Result result = new Result();
        result.setCode(ResultCode.UNAUTHORIZED).setMessage("签名认证失败");
        return result;
    }


    @PostMapping("logOut")
    public Result logOut(HttpSession session) {
        session.removeAttribute("user");
        session.removeAttribute("token");
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return ResultGenerator.genSuccessResult(session.getId());
    }

}
